﻿using OneCard.Face8280Module.Service;

namespace OneCard.Face8280Module.Worker
{
    /// <summary>
    /// 定时刷新缓存
    /// </summary>
    public class RefreshCacheWorker
    {
        public static void Run(IServiceProvider service)
        {
            ILogger<RefreshCacheWorker> Logger = service.GetService<ILogger<RefreshCacheWorker>>();

            Task.Run(async () =>
            {
                do
                {

                    await Task.Delay(600_000);//10分钟强制刷新一次
                    try
                    {
                        //刷新人员表缓存和刷新设备表缓存
                        Logger.LogInformation("开始刷新人员和设备缓存");

                        await RunWorker(service);
                    }
                    catch (Exception )
                    {

                        Logger.LogInformation("刷新人员和设备缓存时 失败");

                    }


                } while (true);
            });
        }

        /// <summary>
        /// 执行工作线程，开始刷新缓存
        /// </summary>
        /// <param name="service"></param>
        /// <returns></returns>
        private static async Task RunWorker(IServiceProvider service)
        {
            DataService db;
            using (var scope = service.CreateScope())
            {
                var myService = scope.ServiceProvider;
                db = myService.GetService<DataService>();
                await db.ReloadCache();
            }
        }
    }
}
